/**
 * 2017年3月8日
 * 二人牛牛
 */
var pomelo = require('pomelo');
var Room = require('./room');
var PlayerManager = require('./playerManager');
var consts = require('./consts');

var utils = require('../../util/utils');

var log = console.log;

var exp = module.exports;

var roomData = {};

// 用户进入游戏
exp.enterGame = function (msg, cb) {

    var self = this;

    // 第一个用户进入时，创建playerManager 即lobby
    if (!this.playerManager) {
        this.playerManager = new PlayerManager();
    }

    this.playerManager.addPlayer(msg, function (err, ret) {
        var room;
        if (err) {
            console.log(err);
            return cb(err, null);
        }
        else {
            // 检查用户是否在房间里的下线列表里
            if (self.playerManager.checkPlayerInRoom(msg.playerId)) {
                room = self.getRoomById(self.playerManager.getRid(playerId));
                if (room.returnPlayer.indexOf(playerId) === -1) {
                    room.returnPlayer.push(playerId);
                }
            }
            return cb(null, ret);
        }
    });
};

// 用户进入房间
// TODO: 进入房间，就从大厅的频道中踢出；退出房间，如果是退到大厅，再加入大厅的频道，如果是退出游戏，就不不再加入大厅的频道。
exp.enterRoom = function (msg, cb) {
    log('用户进入房间： roomManager.enterRoom!', JSON.stringify(msg));

    var self = this;
    var rid = parseInt(msg.rid), playerId = parseInt(msg.playerId), gameId = parseInt(msg.gameId), pos = parseInt(msg.pos);

    var room = self.getRoomById(rid);

    // 检查是否已经登录
    if (!self.playerManager.checkPlayerLogin(playerId)) {
        return cb('player ' + playerId + ' need login to enterRoom!');
    }

    // 检查是否在房间里
    if (self.playerManager.checkPlayerInRoom(playerId)) {
        return cb('player ' + playerId + ' is already in room');
    }

    room.addPlayer(msg, cb);
};

// 用户离开房间
exp.leaveRoom = function (playerId, cb) {
    log('用户离开房间 roomManager.leaveRoom!', playerId);

    if (!this.playerManager.checkPlayerInRoom(playerId)) {
        return cb('player ' + playerId + ' is not in any room!');
    }

    var rid = this.playerManager.getRid(playerId);
    var room = this.getRoomById(rid);

    room.leaveRoom(playerId, cb);
};

/**
 * 获取房间对象
 */
exp.getRoomById = function (rid) {
    log('获取room。rid: %s', rid);
    if (isNaN(parseInt(rid))) {
        throw new Error('rid dataType is invalid! rid: ' + rid);
    }
    var room = roomData[rid];
    if (!room) {
        room = new Room(rid, this.playerManager);
        roomData[rid] = room;
    }
    return room;
};

/**
 * 用户下线
 * 1.检查用户是否在房间里
 * 2.如果在房间里，改变房间中的用户状态；如果不在房间里，直接删掉用户
 */
exp.kick = function (msg) {
    // var msg = { gameId: 5, playerId: '1004', serverId: 'connector-server-1' };
    var self = this;
    var playerId = msg.playerId;
    var rid, room;

    if (self.playerManager.checkPlayerInRoom(playerId)) {
        // 已经进入房间的处理
        // self.leaveRoom(playerId, function (msg) {
        //     log('退出房间回调 roomManager.kick', msg);
        //     self.playerManager.kickPlayer(playerId);
        // });
        rid = this.playerManager.getRid(playerId);
        room = this.getRoomById(rid);

        room.kickGame(playerId, function (err) {
            // self.playerManager.kickPlayer(playerId);
            if (err) {
                log('room.kickGame: ' + err);
            }
            log('已成功将用户 ' + playerId + ' 踢出！');
        });
    }
    else {
        // 只进入大厅的处理
        self.playerManager.kickPlayer(playerId);
    }
};

// 观察游戏
exp.addObserver = function (msg, cb) {
    log('观察游戏 roomManager.observeGame!');
    var playerId = msg.playerId, rid = msg.rid;
    var room = this.getRoomById(rid);

    if (this.playerManager.checkPlayerInRoom(playerId)) {
        return cb('用户已经在房间里！');
    }

    if (room.playerNum !== 2) {
        cb('房间用户数量不符合观察条件！');
    }
    else {
        room.addObserver(msg, cb);
    }
};

// 游戏准备
exp.gameReady = function (msg, cb) {
    log('游戏准备 roomManager.gameReady ', JSON.stringify(msg));

    var rid = msg.rid;
    var room = this.getRoomById(rid);

    room.gameReady(msg, cb);
};

// 下注
exp.bid = function (msg) {
    log('niuniu roomManager.bid caught >>>>>>>>>>>>>>>>>>>>');
    
    var room = this.getRoomById(msg.rid);
    var ret = room.bid(msg);
    return ret;
};

// 申请上庄
exp.applyBanker = function (msg, cb) {
    var roomId = msg.rid;
    roomData[roomId].applyBanker(msg, cb);
};

// 提前结束开牌阶段，进入到下一轮
exp.nextRound = function (msg, cb) {
    log('二人牛牛 roomManager 进入到下一轮！');
    var room = this.getRoomById(msg.rid);
    room.nextRound(msg, cb);
}; 

// 获取才只有一个人的房间号
exp.getWaitRoom = function (cb) {
    var rid = this.playerManager.getWaitRoom();

    cb(null, { rid });
};
